package me.seu.demo.kafka;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.common.Message;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 定义了三个消费者:
 * 1、同组内会均分同主题下分区的消息
 * 2、不同组均会收到主体下全量数据
 *
 * @author liangfeihu
 * @since 2020/3/9 12:08
 */
@Slf4j
@Component
public class KafkaConsumer {

    @KafkaListener(id = "one", topics = {"test_kafka"}, groupId = "me.seu.demo.test-kafka-group")
    public void listenOne(ConsumerRecord<?, ?> record) {
        Optional<?> kafkaMessage = Optional.ofNullable(record.value());
        if (kafkaMessage.isPresent()) {
            Object message = kafkaMessage.get();
            String name = Thread.currentThread().getName();
            log.info("-----------------[{}] [record 1]  = {}", name, record);
            log.info("-----------------[{}] [String msg 1] = {}", name, message);
        }
    }

    @KafkaListener(id = "two", topics = {"test_kafka"}, groupId = "me.seu.demo.test-kafka-group")
    public void listenTwo(ConsumerRecord<?, ?> record) {
        Optional<?> kafkaMessage = Optional.ofNullable(record.value());
        if (kafkaMessage.isPresent()) {
            Object message = kafkaMessage.get();
            String name = Thread.currentThread().getName();
            log.info("-----------------[{}] [record 2] = {}", name, record);
            log.info("-----------------[{}] [String msg 2] = {}", name, message);
        }
    }

    @KafkaListener(topics = {"test_kafka_three"}, groupId = "me.seu.demo.test-kafka-group-2")
    public void listenThree(String msg) {
        String name = Thread.currentThread().getName();
        log.info("-----------------[{}] [String message 3] = {}", name, msg);
        Message message = JSONObject.parseObject(msg, Message.class);
        log.info("-----------------[{}] [Object message 3] = {}", name, message);
    }


}
